import { ref } from 'vue'
import { defineStore } from 'pinia'

const useViewStore = defineStore('view', () => {
  /**
   * 页面标签，内部对象格式（即路由对象）
   * name: '',              //没有 name 的路由不会被缓存
   * path: '',
   * meta: {
       noCache: true        // 为 true 时不缓存
       title: ''            // 路由标题
       noDisplayTag: true   // 为真时，该路由不显示页面标签
       needAuth: true
    }
  */
  const defaultViewTag = {
    path: '/index',
    name: 'Index',
    meta: {
      title: '首页',
    },
  }
  const defaultCachedView = 'Index'
  // 页面标签数据
  const viewTags = ref([defaultViewTag])
  // 缓存的页面名称
  const cachedViewNames = ref([defaultCachedView])

  // 添加缓存的页面
  function addCachedView(route) {
    if (route.meta.noCache || !route.name) return
    if (cachedViewNames.value.includes(route.name)) return
    cachedViewNames.value.push(route.name)
  }
  // 移除缓存的页面
  function removeCachedView(route) {
    const index = cachedViewNames.value.indexOf(route.name)
    if (cachedViewNames.value.length) cachedViewNames.value.splice(index, 1)
  }
  // 重置缓存的页面数组
  function resetCachedViews() {
    cachedViewNames.value = [defaultCachedView]
  }
  
  // 添加页面标签
  function addViewTag(route) {
    if (route.meta.noDisplayTag) return
    let isExisting = viewTags.value.some(tag => tag.path == route.path)
    if (isExisting) return
    viewTags.value.push(route)
  }
  // 移除页面标签
  function removeViewTag(route) {
    let tagIndex = 0
    viewTags.value.forEach((viewTag, index) => {
      if (viewTag.name == route.name) {
        tagIndex = index
      }
    })
    viewTags.value.splice(tagIndex, 1)
  }
  // 重置页面标签
  function resetViewTags() {
    viewTags.value = [defaultViewTag]
  }

  function resetViewStore() {
    resetCachedViews()
    resetViewTags()
  }

  return {
    // 数据
    viewTags,
    cachedViewNames,
    // 方法
    addCachedView,
    removeCachedView,
    resetCachedViews,
    addViewTag,
    removeViewTag,
    resetViewTags,
    resetViewStore,
  }
})

export default useViewStore